package com.ikingtech.platform.service.system.user.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.user.entity.UserDeptDO;
import com.ikingtech.platform.service.system.user.mapper.UserDeptMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tie yan
 */
@Service
public class UserDeptRepository extends ServiceImpl<UserDeptMapper, UserDeptDO> {

    public void removeByUserId(String userId, String tenantCode) {
        this.remove(Wrappers.<UserDeptDO>lambdaQuery()
                .eq(UserDeptDO::getUserId, userId)
                .eq(Tools.Str.isNotBlank(tenantCode), UserDeptDO::getTenantCode, tenantCode));
    }

    public List<String> listUserIdByDeptId(String deptId) {
        return this.listObjs(Wrappers.<UserDeptDO>lambdaQuery()
                .select(UserDeptDO::getUserId)
                .eq(UserDeptDO::getDeptId, deptId), String.class::cast);
    }

    public List<String> listUserIdByDeptIds(List<String> deptIds) {
        List<String> userIds = this.listObjs(Wrappers.<UserDeptDO>lambdaQuery()
                .select(UserDeptDO::getUserId)
                .in(UserDeptDO::getDeptId, deptIds)
                .eq(UserDeptDO::getTenantCode, Me.tenantCode()), String.class::cast);
        return userIds.stream().distinct().collect(Collectors.toList());
    }

    public List<UserDeptDO> listByTenantCodeAndUserIds(String tenantCode, List<String> userIds) {
        if (Tools.Coll.isBlank(userIds)) {
            return new ArrayList<>();
        }
        return this.list(Wrappers.<UserDeptDO>lambdaQuery()
                .in(UserDeptDO::getUserId, userIds)
                .eq(Tools.Str.isNotBlank(tenantCode), UserDeptDO::getTenantCode, tenantCode));
    }

    public List<UserDeptDO> listByUserId(String userId) {
        return this.list(Wrappers.<UserDeptDO>lambdaQuery().in(UserDeptDO::getUserId, userId));
    }

    public List<UserDeptDO> listByDeptIds(List<String> deptIds) {
        if (Tools.Coll.isBlank(deptIds)) {
            return new ArrayList<>();
        }
        return this.list(Wrappers.<UserDeptDO>lambdaQuery().in(UserDeptDO::getDeptId, deptIds));
    }

    public List<String> listDeptIdByUserIds(List<String> userIds) {
        return this.listObjs(Wrappers.<UserDeptDO>lambdaQuery().in(UserDeptDO::getUserId, userIds), String.class::cast);
    }

    public void removeByTenantCode(String tenantCode) {
        this.remove(Wrappers.<UserDeptDO>lambdaQuery().eq(UserDeptDO::getTenantCode, tenantCode));
    }
}
